package com.ceba.test.base.sign.service.impl;

import com.ceba.base.helper.LoggerHelper;
import com.ceba.base.sign.ClientSign;
import com.ceba.base.sign.enums.ErrSign;
import com.ceba.cebacer.EncodeSignType;
import com.ceba.netty.clientSign.IdsClientSign;
import com.ceba.test.base.enums.ResultStatusEnum;
import com.ceba.test.base.helper.SystemHelper;
import com.ceba.test.base.language.ResourceUtils;
import com.ceba.test.base.sign.helper.CheckSignHelper;
import com.ceba.test.base.sign.service.SignInterface;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DigitalSignObject extends SignInterface{

	private static Logger logger = LoggerFactory.getLogger(DigitalSignObject.class);
	private String fileId;
	
	public String getFileId() {
		return fileId;
	}

	public void setFileId(String fileId) {
		this.fileId = fileId;
	}

	public DigitalSignObject(String fileId) {
		this.fileId = fileId; 
	}

	/**
	 * 判断系统是否可用
	 * 1、激活
	 * 2、过期
	 * @return
	 */
	protected  void checkSystemCanSign(ClientSign sign, JSONObject object){
		checkSystemCanSign(object);
		if(!(ErrSign.ERR_0.getCode()+"").equals(object.get("status"))){
			object.put("status", ResultStatusEnum.SB.getCode());
			return ;
		}
		//系统是否还有签名份数
		if(!SystemHelper.isSystemHasLeftSignCount()){
			object.put("status", ResultStatusEnum.SIGNATURES_NUMBER.getCode());
			object.put("message",ErrSign.getLanguageFlag(ErrSign.ERR_6.getCode()));
			return;
		}
		object.put("status",ResultStatusEnum.CG.getCode() );
		return ;

	}



	/**
	 * 数字签名
	 * paramList={"stampList":,"gCertificateServer":}
	 * @throws Exception
	 */
	@Override
	public JSONObject sign(JSONObject paramList, String tempDir, String inFilePath, String outFilePath) throws Exception {
		try{
			JSONObject object  = new JSONObject();
			checkSystemCanSign(null,object);
			if(object.getInt("status")!=0){
				return object;
			}
			//文档签名前是否有sm2签名以及RSA签名
			if(IdsClientSign.getFileHasSm2ByFileId(fileId) && IdsClientSign.getFileHasRSAByFileId(fileId)){
				//当前文档签名类型
				if(IdsClientSign.getEncodeSignTypeByFileId(fileId) == EncodeSignType.SM2.getCode()){
					object.put("status", ResultStatusEnum.SB.getCode());
					object.put("message", ResourceUtils.getMessage("SIGN_FILE_HAS_RSA_SM2_SIGNED"));
					return object;
				}
			}
			if(IdsClientSign.getSignPdf(fileId, outFilePath)){
				object.put("status",ResultStatusEnum.CG.getCode() );
				object.put("message",ResourceUtils.getMessage("SIGNONLY_SIGNATURE_SUCCESS") );
			}else{
				object.put("status", ResultStatusEnum.SB.getCode());
				object.put("message", ResourceUtils.getMessage("MODULES_FAILURE_SIGNATURE"));
			}
			return object;
		}catch(Exception e){
			LoggerHelper.error(logger, e, "");
		}
		return null;
	}
}
